package com.github.baichuan.application.scaffold.dto.resource;


import com.github.baichuan.application.scaffold.domain.authorization.Resource;
import com.github.baichuan.mapping.BeanMapper;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class TreeMapper {
    public List<TreeNode> map(List<Resource> resources){
        List<TreeNode> dtos = new ArrayList<>();

        Stream<Resource> stream = resources.stream();

        List<Resource> roots = stream.filter(x -> x.getParent() == null).sorted(new Resource.SortComparator())
                .collect(Collectors.toList());
        for(Resource resource : roots){
            TreeNode dto = iterationMap(resource, resources);
            dtos.add(dto);
        }
        return dtos;
    }

    private TreeNode iterationMap(Resource resource, List<Resource> resources){
        TreeNode dto = BeanMapper.map(resource, TreeNode.class);
        String parentId = resource.getId();

        List<Resource> children = resources.stream().filter(x -> x.getParent() != null && x.getParent().getId().equals(parentId))
                .sorted(new Resource.SortComparator()).collect(Collectors.toList());
        for(Resource child : children){
            TreeNode childDto = iterationMap(child, resources);
            dto.appendChild(childDto);
        }
        return dto;
    }
}
